﻿using HW.Application.Share.Models;
using HW.Application.Share.Events;
using HW.Core.Ioc;
using Prism.Commands;
using Prism.Mvvm;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HW.Core.Dialog;
using HW.Core.Cache;
using System.Windows.Input;

namespace HW.Application.Login.ViewModels
{
    public class LoginViewModel : ReactiveObject
    {
        [Reactive]
        public CurrentUser CurrentUser { get; set; } = new CurrentUser();

        [Reactive]
        public bool IsAutoLogin { get; set; }

        [Reactive]
        public bool IsRemember { get; set; }

        public ICommand CloseApplicationCommand { get; }

        public LoginViewModel(ICacheManager cacheManager)
        {
            CloseApplicationCommand = new DelegateCommand(() => { PrismProvider.EventAggregator.GetEvent<CloseApplicationEvent>().Publish(); });

            CacheManager = cacheManager;

            //读取登录信息缓存
            LoadUserCache();

            //自动执行登录逻辑
            Task.Delay(1500).ContinueWith(t =>
            {
                if (IsAutoLogin)
                {
                    LoginCommand.Execute();
                }
            });
        }



        //登录逻辑
        public DelegateCommand LoginCommand => new DelegateCommand(() =>
        {
            if (string.IsNullOrEmpty(CurrentUser.UserName) || string.IsNullOrEmpty(CurrentUser.Password))
            {
                return;
            }

            if (IsRemember)
            {
                CacheManager.Set(LoginCacheKey.User, CurrentUser);
            }
            else
            {
                CacheManager.Delete(LoginCacheKey.User);
            }

            CacheManager.Set(LoginCacheKey.IsRemember, IsRemember);
            CacheManager.Set(LoginCacheKey.IsAutoLogin, IsAutoLogin);

            if (CurrentUser.UserName == "admin" && CurrentUser.Password == "123456")
            {
                PrismProvider.EventAggregator.GetEvent<LoginSuccessEvent>().Publish(CurrentUser);
            }
            else
            {
                PopupBox.Show("用户名或密码错误");
            }
        });

        private ICacheManager CacheManager { get; }
        private void LoadUserCache()
        {
            if (CacheManager.Get(LoginCacheKey.User, out CurrentUser user))
            {
                CurrentUser.UserName = user.UserName;
                CurrentUser.Password = user.Password;
            }

            if (CacheManager.Get(LoginCacheKey.IsRemember, out bool isRemember))
            {
                IsRemember = isRemember;
            }

            if (CacheManager.Get(LoginCacheKey.IsAutoLogin, out bool isAutoLogin))
            {
                IsAutoLogin = isAutoLogin;
            }

        }
    }
}
